﻿namespace ColumnOrderingSetup
{
    using System.Reflection;

    using ColumnOrderingSetup.ItemEventReceiver;

    using com.savealot.Extensions.SharePointExtensions;
    using com.savealot.SharePoint;

    using Microsoft.SharePoint;

    public class cobackgroundtask_Definition : BaseDefinition
    {
        #region Fields

        const string LISTNAME = "cobackgroundtask";

        #endregion Fields

        #region Constructors

        public cobackgroundtask_Definition( SPFeatureReceiverProperties properties )
            : base(properties)
        {
        }

        ~cobackgroundtask_Definition( )
        {
            Dispose( false );
        }

        #endregion Constructors

        #region Methods

        public override void Create( )
        {
            base.Create( );
            CreateList( getListDefn( ) );
            addEventReceiver( );
        }

        public override void Delete( )
        {
            base.Delete( );
            deleteEventReciever( );
            DeleteList( getListDefn( ), true );
        }

        void addEventReceiver( )
        {
            using ( SPWeb spWeb = Properties.GetWeb( ) )
            {
                SPList spList = spWeb.Lists.GetListByRootFolder( LISTNAME );
                if ( spList != null )
                {
                    string assemblyFQN = Assembly.GetExecutingAssembly( ).FullName;
                    string classFQN = typeof( COBackgroundTaskItemEventReceiver ).FullName;
                    spList.EventReceivers.Add( SPEventReceiverType.ItemAdded, assemblyFQN, classFQN );
                }
            }
        }

        void deleteEventReciever( )
        {
            using ( SPWeb spWeb = Properties.GetWeb( ) )
            {
                SPList spList = spWeb.Lists.GetListByRootFolder( LISTNAME );
                if ( spList != null )
                {
                    for ( int i = spList.EventReceivers.Count - 1; i >= 0; i-- )
                    {
                        if ( spList.EventReceivers[ i ].Type.Equals( SPEventReceiverType.ItemAdded ) )
                            spList.EventReceivers[ i ].Delete( );
                    }
                }
            }
        }

        ListDefn getListDefn( )
        {
            return new ListDefn
            {
                RootFolderName = LISTNAME,
                Title = LISTNAME,
                Description = "Contains background SPOT tasks.",
                Hidden = true,
                HideExistingContentTypes = false
            };
        }

        #endregion Methods
    }
}